<template>
  <van-nav-bar
    class="search"
    title="修改密码"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-form class="login-form" @submit="onEdit">
    <van-field
      v-model="phone"
      name="手机号"
      label="手机号"
      placeholder="手机号"
      :rules="[{ required: true, message: '请输入手机号' }]"
    />
    <van-field
      v-model="old_password"
      type="password"
      name="原密码"
      label="原密码"
      placeholder="原密码"
      :rules="[{ required: true, message: '请填写原密码' }]"
    />
    <van-field
      v-model="password"
      type="password"
      name="新密码"
      label="新密码"
      placeholder="新密码"
      :rules="[{ required: true, message: '请填写新密码' }]"
    />
    <van-field
      v-model="new_password"
      type="password"
      name="确认密码"
      label="确认密码"
      placeholder="确认密码"
      :rules="[{ required: true, message: '请确认新密码' }]"
    />
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="login">
        修 改
      </van-button>
    </div>
  </van-form>
</template>

<script lang="ts">
import { UserService } from "@/api/user";
import { Notify, Toast } from "vant";
import { reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
export default {
  name: "UserLogin",
  setup() {
    const router = useRouter();
    const data = reactive({
      phone: "",
      password: "",
      old_password: "",
      new_password: "",
    });

    const onClickLeft = () => {
      router.go(-1);
    };
    const onEdit = () => {
      if (data.old_password == "") {
        Notify({ type: "danger", message: "请输入原密码" });
        return;
      }
      if (data.password !== data.new_password) {
        Notify({ type: "danger", message: "请确实两次输入的密码是否一致" });
        return;
      }
      UserService.userinfo().then((res) => {
        if (res.data.code === 112) {
          Notify({ type: "danger", message: "用户未登录" });
        } else {
          UserService.resetPassword({
            password: data.password,
            id: res.data.data.id,
            old_password: data.old_password,
          }).then((r) => {
            if (r.data.code === 0) {
              localStorage.removeItem("token");
              Toast("修改成功");
              router.push({ name: "UserHome" });
            } else {
              Notify({ type: "danger", message: r.data.message });
            }
          });
        }
      });
    };
    return {
      ...toRefs(data),
      onClickLeft,
      onEdit,
    };
  },
};
</script>

<style lang="less" scoped>
.search {
  position: fixed;
  z-index: 999;
  top: 0;
  height: 50px;
  width: 100%;
}
.login-form {
  margin-top: 50px;
}
</style>